package com.run.runbbs.controller;


import com.run.runbbs.common.lang.Result;
import com.run.runbbs.entity.User;
import com.run.runbbs.service.impl.FollowService;
import com.run.runbbs.service.impl.LikeService;
import com.run.runbbs.service.impl.PostService;
import com.run.runbbs.service.impl.UserService;
import com.run.runbbs.util.Constant;
import com.run.runbbs.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;


@RestController
public class UserController implements Constant {
    @Autowired
    private UserService userService;
    @Autowired
    private LikeService likeService;
    @Autowired
    private FollowService followService;
    @Autowired
    private PostService postService;
    @Autowired
    private JwtUtils jwtUtils;

    @GetMapping("/getUserInfo")
    public Result getUserInfo(int userId,HttpServletRequest request){
        int myUserId=0;
        String jwt=request.getHeader("Authorization");
        if(jwt!=null){
            myUserId=Integer.parseInt(jwtUtils.getClaimByToken(jwt).getSubject());
        }


        User user=userService.findUserById(userId);
        //断言,如果为空，抛出异常IllegalArgumentException
        Assert.notNull(user,"用户不存在");
        //用户信息
        Map<String,Object> simpleUser=new HashMap<>();
        simpleUser.put("id",user.getId());
        simpleUser.put("username",user.getUsername());
        simpleUser.put("headerUrl",user.getHeaderUrl());
        //获赞数量
        long likeCount=likeService.findUserLikeCount(userId);
        //关注数量
        long followeeCount=followService.findFolloweeCount(userId,ENTITY_TYPE_USER);
        //粉丝数量
        long followerCount=followService.findFollowerCount(ENTITY_TYPE_USER,userId);
        //是否关注
        boolean hasFollowed=false;
        if(myUserId!=0){
            hasFollowed=followService.hasFollowed(myUserId,ENTITY_TYPE_USER,userId);
        }
        //帖子数量
        long postCount=postService.findPostRows(userId);

        Map<String,Object> info=new HashMap<>();
        info.put("user",simpleUser);
        info.put("postCount",postCount);
        info.put("followeeCount",followeeCount);
        info.put("followerCount",followerCount);
        info.put("likeCount",likeCount);
        info.put("hasFollowed",hasFollowed);

        return Result.success(info);

    }




}
